package com.dianwoba.core.solr;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery.ORDER;

import com.dianwoba.core.solr.where.SolrComplexWhere;
import com.dianwoba.core.solr.where.SolrWhere;

/**
 * SOLR工具类
 * @author 堵成杰
 * @since 2.0
 */
public class SolrUtils{
	
	/**
	 * 格式化SOLR时间
	 * @param date	时间
	 * @return
	 */
	public static String formatDate(Date date){
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
		String str = "";
		try {
			str = sdFormat.format(date);
		} catch (Exception e) {
			return "";
		}
		return str;
	}
	
	/**
	 * 取得排序字段名称
	 * @param sortColumn
	 * @return
	 */
	public static String getSortFieldName(String sortColumn){
		String[] columns = sortColumn.split(" ");
		return columns[0];
	}

	
	/**
	 * 取得排序类型
	 * @param sortColumn
	 * @return
	 */
	public static ORDER getOrder(String sortColumn){
		String[] columns = sortColumn.split(" ");
		if (columns.length >= 2 && StringUtils.contains(columns[1], "desc")) {
			return ORDER.desc;
		}else{
			return ORDER.asc;
		}
	}
	
	/**
	 * 拼装复杂WHERE
	 * @param wheres	where条件
	 * @return
	 */
	public static SolrWhere complexSingleWhere(SolrWhere[] wheres){
		SolrComplexWhere where = new SolrComplexWhere();
		for (SolrWhere innerWhere : wheres) {
			where.and(innerWhere);
		}
		return where;
	}
	
	public static int getTotalHits(List<?> sl){
		assert sl instanceof SolrResultList;
		return (int)((SolrResultList<?>)sl).getTotalHits();
	}
	public static Map<String,Long> getCountMap(String facetName, List<?> sl){
		assert sl instanceof SolrResultList;
		return ((SolrResultList<?>)sl).getCountMap(facetName);
	}
}
